package com.momo.mal.manga.adapter;

import java.util.ArrayList;
import java.util.List;

import net.momo.mal.R;
import com.momo.mal.anime.view.AnimeView;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.entity.Manga;
import com.momo.mal.manga.view.MangaView;
import com.momo.mal.util.AnimeUtil;
import com.momo.mal.util.MangaUtil;
import com.momo.mal.util.AnimeUtil.RequestAnimeUpdate;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

public class MangaListAdapter extends BaseAdapter {
	private List<Manga> mangas = new ArrayList<Manga>();
	private LayoutInflater mInflater;
	private boolean friends;
	private Context context;
	private MalDatabaseAdapter dbAdapter;
	
	public MangaListAdapter(Context context, List<Manga> mangas) {
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		dbAdapter = new MalDatabaseAdapter(context);
		this.mangas = mangas;
		this.friends  = friends;
		this.context = context;
	}

	@Override
	public int getCount() {
		return mangas.size();
	}

	@Override
	public Object getItem(int location) {
		return mangas.get(location);
	}

	@Override
	public long getItemId(int location) {
		return location;
	}

	@Override
	public View getView(final int location, View view, ViewGroup viewgroup) {
		ViewHolder holder;
		if(view == null) {
			holder = new ViewHolder();
			
			view = mInflater.inflate(
					R.layout.manga_list_adapter, null);
			
			holder.title = (TextView) view.findViewById(R.id.text_title);
			holder.volumes = (TextView) view.findViewById(R.id.text_volumes);
			holder.chapters = (TextView) view.findViewById(R.id.text_chapters);
			holder.score = (TextView) view.findViewById(R.id.text_score);
			holder.priority = (TextView) view.findViewById(R.id.text_priority);
			holder.linearView = (LinearLayout) view.findViewById(R.id.linear_view);
			holder.linearMore = (LinearLayout) view.findViewById(R.id.linear_more);
			holder.buttonMore = (ImageButton) view
					.findViewById(R.id.image_button_edit_status);
			
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		
		if (location % 2 == 0) {
			view.setBackgroundColor(Color.WHITE);
		} else {
			view.setBackgroundColor(Color.rgb(217, 229, 250));
		}
		
		if(mangas.get(location).getStatus().equalsIgnoreCase("publishing")) {
			holder.title.setText(Html.fromHtml("<b>" + mangas.get(location).getTitle() + "</b>&nbsp;(Publishing)"));
		} else {
			holder.title.setText(Html.fromHtml("<b>" + mangas.get(location).getTitle() + "</b>"));
		}
		holder.volumes.setText("Volumes : " + mangas.get(location).getVolumesRead() + "/" + mangas.get(location).getVolumes());
		holder.chapters.setText("Chapters : " + mangas.get(location).getChapterRead() + "/" + mangas.get(location).getChapters());
		holder.score.setText("Score : " + mangas.get(location).getScore());
		
		if(mangas.get(location).getPriority() != null) {
			if(mangas.get(location).getPriority().equals("0")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='green'>Low</font>"));
			}
			if(mangas.get(location).getPriority().equals("1")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='yellow'>Med</font>"));
			}
			if(mangas.get(location).getPriority().equals("2")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='red'>High</font>"));
			}
		} else {
			holder.priority.setText(Html.fromHtml("Prio : <font color='green'>Low</font>"));
		}
		
		final View v = holder.buttonMore;
		holder.buttonMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				onClickPopUpMenu(view, location, mangas.get(location).getTitle(), mangas.get(location).getId());
			}
		});
		
		holder.linearMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				onClickPopUpMenu(view, location, mangas.get(location).getTitle(), mangas.get(location).getId());
			}
		});
		
		
		holder.linearView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(context, MangaView.class);
				intent.putExtra("manga_id", mangas.get(location).getId());
				intent.putExtra("title", mangas.get(location).getTitle());
				context.startActivity(intent);
			}
		});
		
		return view;
	}
	
	private class ViewHolder {
		public LinearLayout linearView;
		public LinearLayout linearMore;
		public TextView title;
		public TextView volumes;
		public TextView chapters;
		public TextView score;
		public TextView priority;
		public ImageButton buttonMore;
	}
	
	private void onClickPopUpMenu(View view, final int location, final String title, final String id) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			PopupMenu popup = new PopupMenu(context, view);
			if(mangas.get(location).getReadStatus().equalsIgnoreCase("reading")) {
				popup.getMenuInflater().inflate(R.menu.menu_manga_edit_list_reading,
						popup.getMenu());
			} else {
				popup.getMenuInflater().inflate(R.menu.menu_manga_edit_list,
						popup.getMenu());
			}

			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					// TODO Auto-generated method stub
					if (item.getItemId() == R.id.menu_add_episode) {
						Manga manga = dbAdapter.getMangaById(mangas.get(location).getId());
						int read = Integer.parseInt(manga.getChapterRead()) + 1;
						if(manga.getChapters().equals(String.valueOf(read)) || read > Integer.parseInt(manga.getChapters())) {
							manga.setReadStatus("completed");
							manga.setChapterRead(manga.getChapters());
							manga.setVolumesRead(manga.getVolumes());
							Toast.makeText(context, "You've completed read " + manga.getTitle(), Toast.LENGTH_LONG).show();
						} else {
							manga.setChapterRead(String.valueOf(read));
						}
						
						new MangaUtil().new RequestMangaUpdate(context, dbAdapter.hasManga(manga.getId())).execute(manga);
					}
					if (item.getItemId() == R.id.menu_edit) {
						Manga manga = dbAdapter.getMangaById(mangas.get(location).getId());
						MangaUtil.mangaAddOrUpdatePopUp(manga, context);
					}
					if (item.getItemId() == R.id.menu_more) {
						Intent intent = new Intent(context, MangaView.class);
						intent.putExtra("manga_id", id);
						intent.putExtra("title", title);
						context.startActivity(intent);
					}
					if (item.getItemId() == R.id.menu_delete) {
						AlertDialog.Builder builder = alertDialogDelete(context, title, id);
						builder.create().show();
					}
					if (item.getItemId() == R.id.menu_share) {
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("text/plain");
						intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
						intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/manga/" + id);
						intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);

						context.startActivity(Intent.createChooser(intent, "Share Via ..."));
					}
					return false;
				}

			});
			
			popup.show();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			Resources res = context.getResources();
			builder.setTitle(res.getString(R.string.menu_title));
			
			if(mangas.get(location).getReadStatus().equalsIgnoreCase("reading")) {
				String[] items = {res.getString(R.string.menu_add_chapter),
						res.getString(R.string.menu_edit),
						res.getString(R.string.menu_delete),
						res.getString(R.string.menu_share), 
						res.getString(R.string.menu_information) };
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0) {
							Manga manga = dbAdapter.getMangaById(mangas.get(location).getId());
							int read = Integer.parseInt(manga.getChapterRead()) + 1;
							if(manga.getChapters().equals(String.valueOf(read)) || read > Integer.parseInt(manga.getChapters())) {
								manga.setReadStatus("completed");
								manga.setChapterRead(manga.getChapters());
								manga.setVolumesRead(manga.getVolumes());
								Toast.makeText(context, "You've completed read " + manga.getTitle(), Toast.LENGTH_LONG).show();
							} else {
								manga.setChapterRead(String.valueOf(read));
							}
							
							Log.d("ada g ", dbAdapter.hasManga(manga.getId()) + " asdas");
							new MangaUtil().new RequestMangaUpdate(context, dbAdapter.hasManga(manga.getId())).execute(manga);
						}
						if(which == 1) {
							Manga manga = dbAdapter.getMangaById(mangas.get(location).getId());
							MangaUtil.mangaAddOrUpdatePopUp(manga, context);
						}
						if(which == 2){
							AlertDialog.Builder builder = alertDialogDelete(context, title, id);
							builder.create().show();
						}
						if(which == 3){
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
							intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/manga/" + id);
							intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);
		
							context.startActivity(Intent.createChooser(intent, "Share Via ..."));
						}
						if(which == 4) {
							Intent intent = new Intent(context, MangaView.class);
							intent.putExtra("manga_id", id);
							intent.putExtra("title", title);
							context.startActivity(intent);
						}
					}
				});
			} else {
				String[] items = {res.getString(R.string.menu_edit),
						res.getString(R.string.menu_delete),
						res.getString(R.string.menu_share), 
						res.getString(R.string.menu_information) };
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0) {
							Manga manga = dbAdapter.getMangaById(mangas.get(location).getId());
							MangaUtil.mangaAddOrUpdatePopUp(manga, context);
						}
						if(which == 1){
							AlertDialog.Builder builder = alertDialogDelete(context, title, id);
							builder.create().show();
						}
						if(which == 2){
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
							intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/manga/" + id);
							intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);
		
							context.startActivity(Intent.createChooser(intent, "Share Via ..."));
						}
						if(which == 3) {
							Intent intent = new Intent(context, MangaView.class);
							intent.putExtra("manga_id", id);
							intent.putExtra("title", title);
							context.startActivity(intent);
						}
					}
				});
			}
			
			builder.create().show();
		}
		
	}
	
	private Builder alertDialogDelete(final Context context, String title, final String animeId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("Delete " + title);
		builder.setMessage(Html.fromHtml("Are you sure to delete ?"))
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   new MangaUtil().new RequestMangaDelete(context).execute(new String[] {animeId});
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
	
		return builder;
	}
}
